import React from "react";
import { useImmerReducer } from 'use-immer'
type UserType = typeof defaultState

// 初始状态
const defaultState = { name: "zhangsan", age: -18 }
type ActionType = { type: "UPDATE_NAME", payload: string } | { type: "INCREMENT", payload: number } | { type: "RESET" }

// prevState形参是上一次的旧状态
const reducer = (prevState: UserType, action: ActionType) => {
    console.log("reducer执行了")
    switch (action.type) {
        case "UPDATE_NAME":
            // return { ...prevState, name: action.payload }
            prevState.name = action.payload
            break
        case "INCREMENT":
            // return { ...prevState, age: prevState.age + action.payload }
            prevState.age += action.payload
            break
        case "RESET":
            return defaultState
        default:
            return prevState
    }
}


//形参：初始状态
//返回值：处理好的初始状态
const initAction = (initState: UserType) => {
    // 处理age字段为正整数
    return { ...initState, age: Math.round(Math.abs(initState.age)) || 18 }
}

export const Father: React.FC = () => {

    const [state, dispatch] = useImmerReducer(reducer, defaultState, initAction)
    console.log(state) //{name: 'zhangsan', age: 18}

    const changeState = () => {
        // 直接修改state,打印显示修改成功，但是页面不会更新渲染
        // state.name = 'lisi'
        // console.log(state)

        // dispatch(信息对象)
        dispatch({ type: "UPDATE_NAME", payload: "lisi" })
    }

    return (
        <div>
            <div>{JSON.stringify(state)}</div>
            <button onClick={changeState}>修改用户名</button>
            <div className="father">
                <Son1 {...state} dispatch={dispatch}></Son1>
                <Son2 {...state} dispatch={dispatch}></Son2>
            </div>
        </div>
    )
}

const Son1: React.FC<UserType & { dispatch: React.Dispatch<ActionType> }> = (props) => {
    const { dispatch, ...user } = props
    const add = () => {
        dispatch({ type: "INCREMENT", payload: 1 })
    }
    return (
        <div className="son1">
            <p>{JSON.stringify(user)}</p>
            <button onClick={add}>年龄+1</button>
        </div>
    )
}


const Son2: React.FC<UserType & { dispatch: React.Dispatch<ActionType> }> = (props) => {
    return (
        <div className="son2">
            <p>{JSON.stringify(props)}</p>
            <GrandSon dispatch={props.dispatch} />
        </div>
    )
}



const GrandSon: React.FC<{ dispatch: React.Dispatch<ActionType> }> = (props) => {
    const reset = () => {
        props.dispatch({ type: "RESET" })
    }
    return (
        <>
            <h3>这是GrandSon组件</h3>
            <button onClick={reset}>重置</button>
        </>
    )
}
